<template>
  <div id="text" contenteditable="true" style="padding: 10px" @focus="onFocus" @input="onInput">文本</div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
onMounted(() => {
  let text = document.querySelector('#text') as HTMLDivElement
  let selection = window.getSelection() as Selection
  // setTimeout(() => {
  //   selection.removeAllRanges()
  // }, 2000)
  setTimeout(() => {
    let range = getRange(text)
    let cloneRange = range.cloneRange()
    console.log(range, cloneRange)
    range.insertNode(range.createContextualFragment('hello world<span id="emoji"> emoji</span>'))
    range.collapse(false)
    // selection.removeAllRanges()
    // selection.addRange(cloneRange)
    console.log(cloneRange)

    let emoji = document.querySelector('#emoji') as HTMLElement
    // range.setEndAfter(emoji)
    text.focus()
    // console.log(range, getRange())
  }, 1000)
})

function onFocus(event: FocusEvent) {
  // console.log('focus')
}

// 获取光标
function getRange(element?: HTMLElement) {
  try {
    if (element) {
      element.focus()
    }
    return window.getSelection()?.getRangeAt(0) as Range
  } catch (e) {
    throw '没有选择任何文本'
  }
}

function onInput(event: Event) {
  let range = getRange()

}
</script>

<style lang="scss" scoped></style>
